package com.jch.ft.codec;

import com.jch.ft.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ObjectDecoder extends ByteToMessageDecoder {

    private Class<?> genericClass;

    public ObjectDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) { // 检查字节长度是否满足最小长度
            return;
        }
        // 设置读标记
        in.markReaderIndex();
        // 获取数据长度
        int dataLen = in.readInt();
        if (in.readableBytes() < dataLen) {
            in.resetReaderIndex(); // 重置读标记
            return;
        }

        byte[] dataBytes = new byte[dataLen];
        in.readBytes(dataBytes); // 将制定dataBytes.length长度的字节-传输到dataBytes
        // 转为Java对象
        out.add(SerializationUtil.deserialize(dataBytes,genericClass));
    }
}
